package zcj.stu;

import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletRegistrationBean;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Configuration
public class WebConfig {
    //利用内嵌web容器工厂创建web容器
    @Bean
    public TomcatServletWebServerFactory tomcatServletWebServerFactory(){
        return new TomcatServletWebServerFactory(8888);
    }
    //创建dispatchServlet
    @Bean
    public DispatcherServlet dispatcherServlet(){
        return new DispatcherServlet();
    }
    //将dispatchServlet注册到web容器中
    @Bean
    public DispatcherServletRegistrationBean registrationBean(DispatcherServlet dispatcherServlet){
        DispatcherServletRegistrationBean registrationBean =
                new DispatcherServletRegistrationBean(dispatcherServlet, "/");
        registrationBean.setLoadOnStartup(1);
        return registrationBean;//所有路径
    }
    @Bean
    public BeanNameUrlHandlerMapping mapping(){
        return new BeanNameUrlHandlerMapping();
    }
    @Bean
    public SimpleControllerHandlerAdapter adapter(){
        return new SimpleControllerHandlerAdapter();
    }
    @Component("/c1")
    static class Controller1 implements Controller{

        @Override
        public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
//            response.getWriter().print("<h1>BeanNameUrlHandlerMapping+impleControllerHandlerAdapter</h1>");
            ModelAndView modelAndView = new ModelAndView(new View() {
                @Override
                public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
                    response.getWriter().print("<h1>BeanNameUrlHandlerMapping+impleControllerHandlerAdapter</h1>");
                    response.sendRedirect("c2");

                }
            });
//            response.getWriter().print("<h1>BeanNameUrlHandlerMapping+impleControllerHandlerAdapter</h1>");
            return modelAndView;
        }
    }
}
